<?php
namespace App\Lib;

//旷视 实名认证
class faceid
{
    private $apiKey = '4ojHPQo-13_L6Kq_di7K2MItZzjOsXGi';
    private $apiSecret = '7t8GTpyJ3RsvgHweJrMbJZJxZcO6tqPW';

    private function genSign($apiKey, $apiSecret, $expired){
        $rdm = rand();
        $current_time = time();
        $expired_time = $current_time + $expired;
        $srcStr = "a=%s&b=%d&c=%d&d=%d";
        $srcStr = sprintf($srcStr, $apiKey, $expired_time, $current_time, $rdm);
        $sign = base64_encode(hash_hmac('SHA1', $srcStr, $apiSecret, true).$srcStr);
        return $sign;
    }


    public function getToken($idcardName, $idcardNumber, $bizNo){
        $url = 'https://api.megvii.com/faceid/v3/sdk/get_biz_token';
        $data = [
            'sign' => $this->genSign($this->apiKey, $this->apiSecret, 180),
            'sign_version' => 'hmac_sha1',
            'liveness_type' => 'still',
            'comparison_type' => 1,
            'idcard_name' => $idcardName,
            'idcard_number' => $idcardNumber,
            'biz_no' => $bizNo
        ];
        write_log('faceid', 'get_token', $data);
        $ret_data = curl_request($url, $data, 'urlencoded', 'POST');
        $ret_data = json_decode($ret_data, true);
        write_log('faceid', 'get_token_ret', $ret_data);
        if (isset($ret_data['error'])){
            return null;
        }
        return $ret_data['biz_token'];
    }


    public function verify($bizToken, $dataPath){
        $url = 'https://api.megvii.com/faceid/v3/sdk/verify';
        $data = [
            'sign' => $this->genSign($this->apiKey, $this->apiSecret, 180),
            'sign_version' => 'hmac_sha1',
            'biz_token' => $bizToken,
            'meglive_data' => curl_file_create($dataPath, 'bin', 'meglive_data')
        ];
        write_log('faceid', 'verify', $data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_URL, $url);
        $ret_data= curl_exec($ch);
        curl_close($ch);
        $ret_data = json_decode($ret_data, true);
        write_log('faceid', 'verify_ret', $ret_data);
        if (isset($ret_data['error'])){
            return null;
        }
        return $ret_data;
    }


}
